<template>
    <div class="app">
        <div class="chat_container">
            <div class="main_content_header">实时聊天</div>
            <div class="chat-room">
                <div class="message-item" v-for="(item, index) in messageList" :key="index">
                    <div v-if="item.isSystem" class="system-message">
                        {{ formatSendTime(item.timestamp) }}
                    </div>
                    <!-- 左边通新内容 -->
                    <div class="flex-left" v-if="item.userId !== userInfo.userId">
                        <!--其他人的 头像 -->
                        <div class="avater">
                            <el-avatar src="https://picsum.photos/200/300"></el-avatar>
                        </div>
                        <div class="message-content">{{ item.content }}</div>
                    </div>
                    <div class="flex-right" v-else>
                        <!--自己的 头像 -->
                        <div class="message-content">{{ item.content }}</div>
                        <div class="avater">
                            <el-avatar>
                                <img src="../../../assets/images/avater.jpg" alt="">
                            </el-avatar>
                        </div>
                    </div>
                </div>
            </div>
            <div class="send-box">
                <el-input type="text" v-model="yourMessage" />
                <el-button type="primary" @click="sendMesage">发送</el-button>
            </div>
        </div>
    </div>
</template>

<script setup >
import { onMounted, ref } from 'vue'
const yourMessage = ref('')
const messageList = ref([])
let ws = null
const userInfo = ref({
    userId: ""
})

const user = ref(sessionStorage.getItem('user'))

// 发送消息
function sendMesage() {
    const timestamp = new Date().toISOString()
    if (yourMessage.value) {
        ws.send(JSON.stringify({
            type: "message",
            isSystem: true,
            userId: userInfo.value.userId,
            content: yourMessage.value,
            timestamp: timestamp, // 添加时间戳
        })
        )
        yourMessage.value = ''
    }
}

const initWebSocket = () => {
    ws = new WebSocket(`ws://localhost:8080?user=${String(user.value)}`)
    ws.onopen = () => {
        console.log('链接成功')
        ws.send(JSON.stringify({
            type: "init",
            isSystem: true,
            userId: userInfo.value.userId,
            content: '欢迎来到聊天室',
        })
        )
    }

    ws.onmessage = (e) => {
        const message = JSON.parse(e.data)
        switch (message.type) { // 根据消息类型进行不同的操作
            case "tips":
                console.log(message.content) // 如果消息类型为tips，则打印消息内容

            case 'message':
                messageList.value.push(message) // 如果消息类型为message，则将消息添加到消息列表中

                console.log(messageList.value) // 打印消息列表
                break;
            case 'onlineList':
                onlineList.value = message.onlineList // 如果消息类型为onlineList，则将在线用户列表赋值给onlineList
                break;
        }
    }
    ws.onclose = () => {
        console.log('连接关闭')
    }
    ws.onerror = () => {

    }
}

onMounted(() => {
    userInfo.value.userId = new Date().getTime().toString().slice(8)
    initWebSocket()
})
// 时间格式化
const formatSendTime = (sendTime) => {
    const now = new Date();
    const sendDate = new Date(sendTime);
    const timeDiff = now - sendDate;
    const oneDay = 24 * 60 * 60 * 1000;

    if (timeDiff < 0) {
        return "Invalid time"; // 或者其他错误处理
    }
    if (timeDiff < oneDay) {
        return "今天" + formatTime(sendDate);
    }
    return sendDate.toLocaleDateString("zh-CN") + " " + formatTime(sendDate);
};

const formatTime = (date) => {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return hours + ":" + minutes;
};
</script>


<style lang='less'>
.app {
    // width: 100vw;
    // height: 100vh;
    overflow: hidden;
    // background-color: #fff;
    display: grid;
    place-items: center;

    .chat_container {
        width: 650px;
        height: 650px;
        overflow: hidden;
        background-color: #fff;
        border-radius: 8px;
    }
}

.chat-room {
    height: calc(100% - 110px);
    padding: 10px;
    overflow: auto;
    background: #000;
}

.send-box {
    border-top: 1px solid #eee;
    display: flex;
    align-items: center;
    height: 60px;

}

.message-item {
    width: 100%;
    // margin: 0 auto;
    margin-bottom: 10px;


    .flex-left {
        display: flex;
        justify-content: flex-start;

        .avater {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #eee;
            margin-right: 10px;

        }

        .message-content {
            min-height: 30px;
            height: 40px;
            line-height: 40px;
            background: #fff;
            border-radius: 8px;
            padding: 0 10px;
        }
    }

    .flex-right {
        display: flex;
        justify-content: flex-end;

        .avater {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #eee;
            margin-left: 10px;

        }

        .message-content {
            min-height: 30px;
            height: 40px;
            line-height: 40px;
            background: #fff;
            border-radius: 8px;
            padding: 0 10px;
        }
    }
}

.main_content_header {
    width: 100%;
    height: 50px;
    border-radius: 5px;
    background-color: #7de0bd;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
}

.system-message {
    font-size: 12px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>